<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate"
          >&emsp;新增&emsp;
          </el-button
          >
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table
          ref="dataList"
          :data="menuList"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          class="w-full mb-4"
          row-key="id"
        >
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="标题" prop="title"></el-table-column>
          <!-- <el-table-column prop="message_type" label="消息类型">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.message_type === 1"
                >文字</el-tag
              >
              <el-tag type="primary" v-if="scope.row.message_type === 2"
                >图片</el-tag
              >
            </template>
          </el-table-column> -->
          <el-table-column label="内容" min-width="300px" prop="content">
            <template slot-scope="scope">
              <div v-if="scope.row.message_type === 2">
                <img
                  v-for="(item, index) in scope.row.content"
                  :key="index"
                  :src="item"
                  style="width:80px;height:80px;margin:5px;"
                />
              </div>
              <div
                v-if="scope.row.message_type === 1"
                v-html="scope.row.content"
              ></div>
            </template>
          </el-table-column>
          <el-table-column label="时间" prop="add_time"></el-table-column>

          <el-table-column label="操作" width="260px">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button>
              <el-button
                icon="el-icon-delete"
                plain
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
              <el-button
                icon="el-icon-position"
                plain
                size="mini"
                type="success"
                @click="handleSend(scope.row)"
              >发送
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""
      ><em style="font-style:normal;color:red">删除后不可恢复</em
      >，你还要继续吗？</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleCloseDialog"
      @opened="initWangEditor"
    >
      <el-form
        ref="editRulesForm"
        :model="editRulesForm"
        :rules="editRulesFormRules"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="editRulesForm.title"
            clearable
            placeholder="请输入标题文字(1-30个字符)"
          ></el-input>
        </el-form-item>
        <el-form-item label="消息类型" prop="message_type">
          <el-radio-group v-model="editRulesForm.message_type">
            <el-radio :label="1" border>文字</el-radio>
            <!-- <el-radio border :label="2">图片</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div v-show="editRulesForm.message_type === 1" style="height:326px">
            <div id="wang_editor" ref="wang_editor"></div>
          </div>
          <div v-show="editRulesForm.message_type === 2">
            <el-upload
              :auto-upload="true"
              :file-list="editShowPirtureList"
              :http-request="customizeUpload"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              action=""
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')"
          >提交
          </el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 发送弹出框 -->
    <el-dialog v-dialogDrag :visible.sync="sendVisible" title="发送">
      <el-form
        ref="sendForm"
        :model="sendForm"
        :rules="sendFormRules"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="发送内容">
          <div v-if="sendMessageType === 2">
            <img
              v-for="(item, index) in sendContent"
              :key="index"
              :src="item"
              style="width:80px;height:80px;margin:5px;"
            />
          </div>
          <div v-if="sendMessageType === 1" v-html="sendContent"></div>
        </el-form-item>
        <el-form-item label="发送用户" prop="user_type">
          <el-select v-model="sendForm.user_type" placeholder="请选择用户类型">
            <el-option
              v-for="item in chooseUser"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="sendForm.user_type === 2"
          label="用户编号(多个用逗号隔开)"
          prop="user_codes"
        >
          <el-input
            v-model="sendForm.user_codes"
            placeholder="请输入用户ID"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="sendVisible = false">返回</el-button>
          <el-button type="primary" @click="sendSubmit">发送</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, listData, postAddData, postSendData, putEditData } from '@/api/sys/sysMessages'

import wangEditor from 'wangeditor'

const notice = {
  type: 'success',
  message: '操作成功',
  position: 'bottom-right',
  showClose: false,
  duration: 3000
}

export default {
  data() {
    return {

      sendContent: undefined,
      sendMessageType: 1,
      chooseUser: [
        { value: 1, label: '全部' },
        { value: 2, label: '指定' },
        { value: 3, label: '男性' },
        { value: 4, label: '女性' }
      ],
      sendVisible: false,
      sendFormRules: {
        user_type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
        // user_codes:[{required:true,message:'请输入用户ID',trigger:'blur'}]
      },
      sendForm: {
        user_type: undefined,
        user_codes: undefined
      },
      editShowWord: '',
      wangEdit: null, // wangeditor 编辑器
      editShowPirtureList: [],

      // 上传图片
      dialogImageUrl: '',
      // 富文本框
      editorOption: {},
      // 要修改的当前行的id
      row_id: 0,
      // 黑名单类别
      blackList: [
        { value: 1, label: '1' },
        { value: 2, label: '4' },
        { value: 3, label: '6' },
        { value: 4, label: '3' },
        { value: 5, label: '5' }
      ],
      // 选中的黑名单类别
      checkBlackList: [],
      provinceList: [],
      cityList: [],
      // 表单规则
      editRulesFormRules: {
        title: [
          { required: true, message: '请输入标题文字', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '标题文字控制在1-30个字符内',
            trigger: 'blur'
          }
        ],
        message_type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      // 受限类型
      limit_typeList: [
        { value: 0, label: '全部' },
        { value: 1, label: 'IP' },
        { value: 2, label: '归属地' }
      ],
      editRulesForm: {
        title: '',
        message_type: 0,
        content: ''
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '新增'
      },
      pirtureList: [],
      uploadPirtureList: [],
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perpage: 10
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: '',
      timeout: null // 定时器
    }
  },
  created() {
    this.getList()
  },
  methods: {
    initWangEditor() {
      this.wangEdit = new wangEditor(this.$refs['wang_editor'])
      this.wangEdit.config.height = 250
      this.wangEdit.config.uploadFileName = 'file'
      this.wangEdit.config.uploadImgHooks = {
        customInsert: (insertImgFn, { data }) => insertImgFn(data.url)
      }
      this.wangEdit.config.onchange = newHtml => (this.editShowWord = newHtml)
      this.wangEdit.create()
    },
    handleSend(row) {
      this.row_id = row.id
      this.sendMessageType = row.message_type
      this.sendContent = row.content
      this.sendVisible = true
    },
    sendSubmit() {
      this.$refs.sendForm.validate(valid => {
        if (valid) {
          if (this.sendForm.user_type === 2) {
            if (
              this.sendForm.user_codes === undefined ||
              !this.sendForm.user_codes.trim()
            ) {
              this.$message.warning('请输入用户编号')
              return
            }
          } else {
            this.sendForm.user_codes = undefined // 置空
          }
          postSendData(this.row_id, this.sendForm).then(response => {
            if (response.code === 200) {
              // this.getList()
              this.sendVisible = false
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
            }
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }

      listData(urlData).then(response => {
        this.menuList = response.data.list
        this.menuList.forEach(item => {
          if (item.message_type === 2) {
            item.content = item.content.split(';')
          }
        })
        this.total = response.data.meta.total
        this.listLoading = false
      })
    },
    // 点击新增
    handleCreate() {
      this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      this.row_id = row.id
      this.editRulesForm.title = row.title
      this.editRulesForm.message_type = row.message_type

      if (this.editRulesForm.message_type === 1) {
        this.editRulesForm.content = row.content
        let time = setTimeout(() => {
          this.wangEdit.txt.html(row.content)
          clearTimeout(time)
        }, 500)
      } else {
        this.editRulesForm.content = row.content.join(';')
        row.content.forEach(item => {
          this.editShowPirtureList.push({
            status: 'success',
            uid: this._.random(1e10),
            url: item
          })
        })
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },

    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.cityList = []
        this.editRulesForm = {
          title: undefined,
          message_type: 1,
          content: undefined
        }
      })
    },
    // 移除图片
    handleRemove(file, fileList) {
      this.editShowPirtureList = fileList
    },
    handleSuccess(_, { status, uid }) {
      this.editShowPirtureList.push({ status, url: this.ossLastImgUrl, uid })
    },
    handleCloseDialog() {
      this.$refs['wang_editor'].innerHTML = ''
      this.wangEdit.destroy()
      this.wangEdit = null
      this.editShowPirtureList = []
      this.editShowWord = ''
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.dialogStatus === 'create') {
            let obj = JSON.parse(JSON.stringify(this.editRulesForm))
            const content = this.editShowPirtureList
              .map(pic => pic.url)
              .join(';')
            if (this.editRulesForm.message_type === 2) {
              obj.content = content
            } else {
              obj.content = this.editShowWord
            }
            postAddData(obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify(notice)
              }
            })
          } else {
            let obj = JSON.parse(JSON.stringify(this.editRulesForm))
            if (this.editRulesForm.message_type === 2) {
              let tempList = []
              this.editShowPirtureList.forEach(item => {
                if (item.response) {
                  tempList.push(item.response.data.url)
                } else {
                  tempList.push(item.url)
                }
              })
              obj.content = tempList.join(';')
            } else {
              obj.content = this.editShowWord
            }
            putEditData(this.row_id, obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify(notice)
              }
            })
          }
        }
      })
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { ids: ids }
      }

      this.deleteDialogVisible = false
      deleteData(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
    }
  },
  watch: {
    sendVisible(value) {
      if (!value) {
        this.$refs['sendForm'].resetFields()
      }
    }
  },
  beforeDestroy() {
    this.wangEdit = null
    this.editShowWord = ''
    clearTimeout(this.timeout)
  }
}
</script>

<style scoped></style>
